package com.lsh.oms.provider.service.status;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.api.model.order.OrderHeadDTO;
import com.lsh.oms.api.model.order.OrderHeadUpdateDTO;
import com.lsh.oms.api.model.status.UpdateStatusDto;
import com.lsh.oms.api.service.status.IUpdateStatusService;
import com.lsh.oms.core.constant.Constants;
import com.lsh.oms.core.constant.HttpConstant;
import com.lsh.oms.core.constant.LoggerConstant;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.OrderOperateType;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.enums.YN;
import com.lsh.oms.core.model.http.HttpMessage;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.order.OrderHeadExt;
import com.lsh.oms.core.model.order.OrderShippingHead;
import com.lsh.oms.core.model.order.OrderShippingHeadWithBLOBs;
import com.lsh.oms.core.proxy.service.DmallProxy;
import com.lsh.oms.core.proxy.service.EsProxy;
import com.lsh.oms.core.proxy.service.TmsProxy;
import com.lsh.oms.core.redis.RedisTemplate;
import com.lsh.oms.core.service.asynservice.OmsEventBus;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.order.OrderUpdateService;
import com.lsh.oms.core.service.other.ShippingOrderService;
import com.lsh.oms.core.service.status.BillAdapterService;
import com.lsh.oms.core.service.tms.TmsService;
import com.lsh.oms.core.service.tool.ToolService;
import com.lsh.oms.core.utils.ResultVo;
import com.lsh.oms.core.utils.ShopCheckUtils;
import com.lsh.oms.provider.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author peter
 */
@Service(protocol = "rest")
@Path("order/status")
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public class OrderStatusRestServiceImpl extends BaseService implements IUpdateStatusService {

    private static Logger logger = LoggerFactory.getLogger(OrderStatusRestServiceImpl.class);

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private OrderUpdateService orderUpdateService;

    @Autowired
    private BillAdapterService billAdapterService;

    @Autowired
    private ShippingOrderService shippingOrderService;

    @Autowired
    private TmsService tmsService;

    @Autowired
    private EsProxy esProxy;

    @Autowired
    private TmsProxy tmsProxy;

    @Autowired
    private DmallProxy dmallProxy;

    @Autowired
    private RedisTemplate redisTemplate;

//    public static final String PUSH_KEY = "oms:dmall:ship:time:push:";

    @Value("${isPro}")
    private String isPro;

    @Value("${shopUrl}")
    private String shopUrl;

    @Value("${calUrl}")
    private String calUrl;

    @Value("${signCalUrl}")
    private String signCalUrl;

//    @Value("${smsUrl}")
//    private String smsUrl;

    @Value("${tms.host}")
    private String tmsHost;

    /**
     * 已提交DC更新为已分拣 发货是调用   TODO 发货接口已处理  （2020-1-2）
     *
     * @param dto
     * @return
     */
    @POST
    @Path("update/tms/sorting")
    @Override
    @Deprecated
    public CommonResult<Object> updateStatusTmsSorting(UpdateStatusDto dto) {
        String logSign = "logSign : " + ToolService.getLogSign();
        long startTimeMs = System.currentTimeMillis();
        logger.info(logSign + " : 更新订单状态（分拣）入参 －－ "
                + (dto == null ? "" : JsonUtils.obj2Json(dto)), LoggerConstant.LOGGER_INFO);
        CommonResult<Object> result = new CommonResult<>();
        if (!checkCommonParams(dto)) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setMessage("update-tms-sorting请求参数不合法，请检验。");
            return result;
        }
        OrderHead headDto = orderQueryService.findByCode(dto.getOrderNo(), false, false);
        if (headDto == null) {
            result = new CommonResult<>(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
            return result;
        }

        if (!headDto.getOrderStatus().equals(OrderStatus.ORDER_WM_NEW.getIndex())) {
            if (headDto.getOrderStatus().equals(OrderStatus.ORDER_SORTING.getIndex())) {
                result.setCode(ReturnCode.REQUEST_SUCCESS);
                result.setData(true);
                result.setMessage("订单状态已经是已分拣，请检验。");
            } else {
                result.setCode(ReturnCode.ORDER_STATUS_ERROR);
                result.setData(false);
                result.setMessage("订单状态不可操作，请检验。");
            }
            return result;
        }

        dto.setStatus(OrderStatus.ORDER_SORTING.getIndex());
        dto.setId(headDto.getId());
        OrderHead entity = new OrderHead();
        boolean resultUpdate = orderUpdateService.updateOrderStatus(headDto.getOrderCode(), entity, OrderOperateType.ORDER_SORTING, this.getVenderId()) >= 1;
        if (resultUpdate) {
            sendEs4order(dto.getOrderNo(), OrderStatus.ORDER_SORTING.getIndex(), logSign);
        }

        logger.info(logSign + "--: 更新DB订单状态－－ " + resultUpdate + "," + (startTimeMs - System.currentTimeMillis()) + "ms");
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData((resultUpdate));
        result.setMessage("");
        logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
        return result;
    }

    /**
     * 更新订单es
     *
     * @param orderCode 参数
     * @param logSign   参数
     */
    private void sendEs4order(Long orderCode, Integer orderStatus, String logSign) {
        OrderHead orderHead = new OrderHead(orderCode, orderStatus);
        esProxy.editIndex(EsProxy.transformToOrderHeadForEs(orderHead), logSign);
    }

    /**
     * 更新发货es
     *
     * @param shippingHead 参数
     * @param logSign      参数
     */
    private void sendEs4shipping(OrderShippingHead shippingHead, String logSign) {
        OrderShippingHeadWithBLOBs oshEs = new OrderShippingHeadWithBLOBs();
        oshEs.setShippingOrderId(shippingHead.getShippingOrderId());
        oshEs.setStatus(shippingHead.getStatus());
        logger.info(logSign + "ES入参修改发货是-- " + JsonUtils.obj2Json(oshEs));
        esProxy.editIndex(oshEs, logSign);
    }

    /**
     * 已分拣更新为已发货
     *
     * @param dto 参数
     * @return 返回值
     */
    @POST
    @Path("update/tms/delivery")
    @Override
    public CommonResult<Object> updateStatusTmsDelivery(UpdateStatusDto dto) {
        String logSign = "logSign : " + ToolService.getLogSign();
        long startTimeMs = System.currentTimeMillis();
        logger.info(logSign + " : 更新订单状态（发货）入参: " + JsonUtils.obj2Json(dto));
        CommonResult<Object> result = new CommonResult<>();
        if (!checkCommonParams(dto)) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setMessage("update-tms-delivery 请求参数不合法，请检验。");
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
        OrderHead orderHead = orderQueryService.findByCode(dto.getOrderNo(), false, false);
        if (orderHead == null) {
            result = new CommonResult<>(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }

        if (!orderHead.getOrderStatus().equals(OrderStatus.ORDER_SORTING.getIndex())) {
            if (orderHead.getOrderStatus().equals(OrderStatus.ORDER_DELIVERY.getIndex())) {
                result.setCode(ReturnCode.REQUEST_SUCCESS);
                result.setData(true);
                result.setMessage("订单状态已经是已发货，请检验。");
            } else {
                result.setCode(ReturnCode.ORDER_STATUS_ERROR);
                result.setData(false);
                result.setMessage("订单状态不可操作，请检验。");
            }

            return result;
        }

        // 数据库与es一致
        OrderShippingHead shippingHead = new OrderShippingHead();
        boolean updateFlag = this.tmsService.dealDelivery(orderHead, shippingHead);
        if (updateFlag) {
            this.sendEs4order(dto.getOrderNo(), OrderStatus.ORDER_DELIVERY.getIndex(), logSign);
            this.sendEs4shipping(shippingHead, logSign);

            this.notifyDmall(orderHead);
        }

        logger.info(logSign + " --: 更新DB订单状态－－ " + updateFlag);
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(updateFlag);
        result.setMessage("");
        logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
        return result;
    }

    private void notifyDmall(OrderHead orderHead){

        JSONObject orderext = JSON.parseObject(orderHead.getAddressInfo());
        String dmallOrderId = orderext.getString("DuoDianOrderId");

        if(StringUtils.isEmpty(dmallOrderId)){
            return;
        }

        OrderShippingHead orderShippingHead = shippingOrderService.selectOneByOrderCode(orderHead.getOrderCode(), false);
        if (null == orderShippingHead) {
            logger.info(orderHead.getOrderCode() + " 发货单未找到");
            return;
        }
        Long tranUid = orderShippingHead.getTransUid();
        if (null == tranUid || tranUid == 0L) {
            logger.info(orderHead.getOrderCode() + " 司机信息不存在 tranUid " + tranUid);
            return;
        }
        JSONArray contents = this.getTranInfo(orderShippingHead);
        if (null == contents || contents.isEmpty()) {
            logger.info(orderShippingHead.getShippingOrderId() + " 司机信息查找失败 " + orderShippingHead.getTransUid());
            return;
        }
        JSONObject tranInfo = contents.getJSONObject(0);
        if (null == tranInfo) {
            logger.info(orderShippingHead.getShippingOrderId() + " 司机信息查找失败 null " + orderShippingHead.getTransUid());
            return;
        }

        try {
            JSONObject req = new JSONObject();
            req.put("orderId", dmallOrderId);
            req.put("processTime", orderShippingHead.getActivedAt().longValue() * 1000);
            req.put("deliveryId", orderShippingHead.getTransUid());
            req.put("deliveryName", tranInfo.getString("name"));
            req.put("deliveryTel", tranInfo.getString("cellphone"));

            if (dmallProxy.pushShipDmall(req)) {
                redisTemplate.set(Constants.PUSH_SHIPPING_TIME_KEY + orderHead.getOrderCode(), "push");
            } else {
                logger.info("【推送多点订单配送中】失败订单号-fail {}", orderHead.getOrderCode());
            }
        } catch (Exception e) {
            logger.error("【推送多点订单配送中】异常订单号-fail {}", orderHead.getOrderCode());
        }

    }

    /**
     * 获取司机信息
     *
     * @param orderShippingHead
     * @return
     */
    private JSONArray getTranInfo(OrderShippingHead orderShippingHead) {

        JSONArray contents = null;
        try {
            HttpMessage httpMessage = this.tmsProxy.getTranInfo("", orderShippingHead.getTransUid(), orderShippingHead.getVenderId());
            logger.info(orderShippingHead.getShippingOrderId() + " 查询司机信息" + JSON.toJSONString(httpMessage));
            if (httpMessage.getStatus().equals("200")) {
                OrderShippingHeadWithBLOBs update = new OrderShippingHeadWithBLOBs();
                update.setId(orderShippingHead.getId());

                String message = httpMessage.getMessage();
                if (org.apache.commons.lang3.StringUtils.isBlank(message)) {
                    return null;
                }

                JSONObject messageJson = JSONObject.parseObject(message);
                if (null == messageJson || messageJson.getInteger("ret") != 0) {
                    return null;
                }
                contents = messageJson.getJSONArray("content");
                if (null == contents) {
                    return null;
                }
            }

        } catch (Exception ex) {
            logger.error("查询司机信息 失败", ex);
            contents = null;
        }

        return contents;

    }

    /**
     * 已分拣、已发货更新为已签收  , TODO 签收单生成接口完成 （2020-1-3）
     *
     * @param dto 参数
     * @return 返回值
     */
    @POST
    @Path("update/tms/sign")
    @Override
    @Deprecated
    public CommonResult<Object> updateStatusTmsSign(UpdateStatusDto dto) {
        String logSign = "logSign : " + ToolService.getLogSign();
        long startTimeMs = System.currentTimeMillis();
        logger.info(logSign + " : 更新订单状态(签收)入参 " + (dto == null ? "" : JsonUtils.obj2Json(dto)));
        CommonResult<Object> result = new CommonResult<>();
        if (!checkCommonParams(dto)) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setMessage("update-tms-sign 请求参数不合法，请检验。");
            return result;
        }
        OrderHead orderHead = this.orderQueryService.findByCode(dto.getOrderNo(), false, false);
        if (orderHead == null) {
            result = new CommonResult<>(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
            return result;
        }
        logger.info(logSign + " --updateStatusTmsSign order orderStatus is -- " + orderHead.getOrderStatus());

        if (orderHead.getOrderStatus().equals(OrderStatus.ORDER_DELIVERY.getIndex()) || orderHead.getOrderStatus().equals(OrderStatus.ORDER_SORTING.getIndex())) {
            OrderShippingHead shippingHead = new OrderShippingHead();
            Boolean resultUpdate = this.tmsService.dealSign(orderHead, shippingHead);
            if (null != resultUpdate && resultUpdate){
                this.sendEs4order(dto.getOrderNo(), OrderStatus.ORDER_SIGN.getIndex(), logSign);
                this.sendEs4shipping(shippingHead, logSign);
            }
            logger.info(logSign + " --: 更新DB订单状态－－ " + resultUpdate);
            result.setCode(ReturnCode.REQUEST_SUCCESS);
            result.setData(resultUpdate);
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            result.setMessage("");
        } else {
            if (orderHead.getOrderStatus() == OrderStatus.ORDER_SIGN.getIndex()) {
                result.setCode(ReturnCode.REQUEST_SUCCESS);
                result.setData(true);
                result.setMessage("签收成功");
            } else {
                result.setCode(ReturnCode.ORDER_STATUS_ERROR);
                result.setData(false);
                result.setMessage("订单状态不可操作，请检验。");
            }
        }

        if (result.getCode().equals(ReturnCode.REQUEST_SUCCESS)) {
            OmsEventBus.post(dto);
        }

        logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
        return result;
    }

    /**
     * 参数检查
     *
     * @param dto 参数
     * @return 返回值
     */
    private boolean checkCommonParams(UpdateStatusDto dto) {
        if (dto == null || StringUtils.isEmpty(dto.getErp())) {
            return false;
        }
        if (dto.getOrderNo() == null) {
            return false;
        }

        return true;
    }

    /**
     * 由未编辑更新为可提交DC
     *
     * @param dto 参数
     * @return 返回值
     */
    @POST
    @Path("update/edit")
    @Override
    public CommonResult<Object> updateStatusNoEdit(UpdateStatusDto dto) {
        String logSign = "logSign:" + ToolService.getLogSign() + ",";
        logger.info(logSign + " : 更新订单状态（客服审核）入参 －－ {}", JsonUtils.obj2Json(dto));
        CommonResult<Object> result = new CommonResult<>();
        if (!checkCommonParams(dto)) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setMessage("update-edit 请求参数不合法，请检验。");
            return result;
        }

        Long venderId = this.getVenderId();

        OrderHead headDto = orderQueryService.findByCode(dto.getOrderNo(), false, false);
        if (headDto == null) {
            result = new CommonResult<>(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
            return result;
        }
        if (!headDto.getOrderStatus().equals(OrderStatus.ORDER_NO_EDIT.getIndex())) {
            if (headDto.getOrderStatus().equals(OrderStatus.ORDER_SPLIT_CHECK.getIndex())) {
                result.setCode(ReturnCode.REQUEST_SUCCESS);
                result.setData(true);
                result.setMessage("订单状态已经是" + OrderStatus.ORDER_SPLIT_CHECK.getName() + "，请检验。");
            } else {
                result.setCode(ReturnCode.ORDER_STATUS_ERROR);
                result.setData(false);
                result.setMessage("订单状态不可操作，请检验。");
            }
            return result;
        }
        boolean checkFlag = ShopCheckUtils.checkMarketInfo4Position(headDto.getAddressInfo());

        if (!checkFlag) {
            result.setCode(ReturnCode.ORDER_ADDRESS_INFO_ERROR);
            result.setData(false);
            result.setMessage("订单的addressInfo不合法，请检验。");
            return result;
        }

        OrderHead entity = new OrderHead();
        entity.setIsMp(YN.Y.getValue());
        boolean resultUpdate = orderUpdateService.updateOrderStatus(headDto.getOrderCode(), entity, OrderOperateType.ORDER_AUDIT, venderId) == 1;
        if (resultUpdate) {
            this.sendEs4order(dto.getOrderNo(), OrderStatus.ORDER_SPLIT_CHECK.getIndex(), logSign);
        }
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(resultUpdate);
        result.setMessage("ok");
        return result;
    }

    /**
     * 由已送达更新为已完成
     *
     * @param dto 参数
     * @return 参数
     */
    @POST
    @Path("update/comment")
    @Override
    public CommonResult<Object> updateStatusComment(UpdateStatusDto dto) {
        String logSign = "logSign:" + ToolService.getLogSign() + ",";
        long startTimeMs = System.currentTimeMillis();
        logger.info(logSign + " : 更新订单状态（评论）入参 －－ "
                + (dto == null ? "" : JsonUtils.obj2Json(dto)), LoggerConstant.LOGGER_INFO);
        CommonResult<Object> result = new CommonResult<>();
        if (!checkCommonParams(dto)) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setMessage("update-comment 请求参数不合法，请检验。");
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
        OrderHead headDto = orderQueryService.findByCode(dto.getOrderNo(), false, false);
        if (headDto == null) {
            result = new CommonResult<>(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
        if (!headDto.getOrderStatus().equals(OrderStatus.ORDER_SIGN.getIndex())) {
            if (headDto.getOrderStatus().equals(OrderStatus.ORDER_FINISH.getIndex())) {
                result.setCode(ReturnCode.REQUEST_SUCCESS);
                result.setData(true);
                result.setMessage("订单状态已经是" + OrderStatus.ORDER_FINISH.getName() + "，请检验。");
            } else {
                result.setCode(ReturnCode.ORDER_STATUS_ERROR);
                result.setData(false);
                result.setMessage("订单状态不可操作，请检验。");
            }
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
//        dto.setStatus(OrderStatus.ORDER_FINISH.getIndex());
//        dto.setId(headDto.getId());
        OrderHead entity = new OrderHead();
        entity.setIsMp(YN.Y.getValue());
        boolean resultUpdate = orderUpdateService.updateOrderStatus(headDto.getOrderCode(), entity, OrderOperateType.ORDER_FINISH, this.getVenderId()) == 1;
        if (resultUpdate) {
            OrderHead orderHead = new OrderHead(dto.getOrderNo(), OrderStatus.ORDER_FINISH.getIndex());
            OrderHeadExt ext = new OrderHeadExt();
            ext.setIsComment(dto.getIsComment());
            esProxy.editIndex(EsProxy.transformToOrderHeadForEs(orderHead, ext), logSign);
        }
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(resultUpdate);
        result.setMessage("");
        logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
        return result;
    }

    /**
     * 司机错签,由已送达、已完成更新为已发货
     *
     * @param dto 参数
     * @return 返回值
     */
    @POST
    @Path("update/tms/returnDelivery")
    @Override
    public CommonResult<Object> updateStatusTmsReturnDelivery(UpdateStatusDto dto) {
        String logSign = "logSign:" + ToolService.getLogSign() + ",";
        long startTimeMs = System.currentTimeMillis();
        logger.info(logSign + " : 更新订单状态（误签收）入参 －－ "
                + (dto == null ? "" : JsonUtils.obj2Json(dto)), LoggerConstant.LOGGER_INFO);

        CommonResult<Object> result = new CommonResult<>();
        if (!checkCommonParams(dto)) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setMessage("update-tms-returnDelivery 请求参数不合法，请检验。");
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
        OrderHead headDto = orderQueryService.findByCode(dto.getOrderNo(), false, false);

        if (headDto == null) {
            result = new CommonResult<>(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
        boolean checkStatus = checkStatusReturnDelivery(headDto);

        if (!checkStatus) {
            if (headDto.getOrderStatus().equals(OrderStatus.ORDER_DELIVERY.getIndex())) {
                result.setCode(ReturnCode.REQUEST_SUCCESS);
                result.setData(true);
                result.setMessage("订单状态已经是" + OrderStatus.ORDER_DELIVERY.getName() + "，请检验。");
            } else {
                result.setCode(ReturnCode.ORDER_STATUS_ERROR);
                result.setData(false);
                result.setMessage("订单状态不可操作，请检验。");
            }
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
        dto.setStatus(OrderStatus.ORDER_DELIVERY.getIndex());
        dto.setId(headDto.getId());
        OrderHead entity = new OrderHead();
        entity.setLackDeliveryType(dto.getLackDeliveryType());
//        boolean updateFlag = orderUpdateService.updateOrderStatus(headDto.getOrderCode(), entity, OrderOperateType.ORDER_STATUS_ROLLBACK_2_DELIVERED, this.getVenderId()) >= 1;
        boolean updateFlag = billAdapterService.reNew(headDto.getOrderCode(), entity, OrderOperateType.ORDER_STATUS_ROLLBACK_2_DELIVERED, this.getVenderId());
//        if (updateFlag) {
//            sendEs4order(dto.getOrderNo(), OrderStatus.ORDER_DELIVERY.getIndex(), logSign);
//        }
        logger.info(logSign + " --: 更新DB订单状态－－ " + updateFlag);
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(updateFlag);
        result.setMessage("");
        logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
        return result;
    }

    /**
     * 参数检查
     *
     * @param headDto 参数
     * @return 返回值
     */
    private boolean checkStatusReturnDelivery(OrderHead headDto) {
        if (headDto == null) {
            return false;
        }
        if (headDto.getOrderStatus() == OrderStatus.ORDER_FINISH.getIndex() || headDto.getOrderStatus() == OrderStatus.ORDER_SIGN.getIndex() || headDto.getOrderStatus() == OrderStatus.ORDER_FINISH.getIndex()) {
            return true;
        }

        return false;
    }

    /**
     * 修改订单地址信息
     *
     * @param orderHeadUpdateDTO 修改参数
     * @return
     * @Path("update/mis/shophead")
     */
    @POST
    @Path("update/mis/shophead")
    @Override
    public CommonResult<Object> updateStatusMisShopHead(OrderHeadUpdateDTO orderHeadUpdateDTO) {
        logger.info("logSign:orderHead:param is " + JSON.toJSONString(orderHeadUpdateDTO));
        String logSign = "logSign:orderHead" + ToolService.getLogSign() + ",";
        CommonResult<Object> result = new CommonResult<>();
        if (!checkMisOrder(orderHeadUpdateDTO)) {
            result.setCode(ReturnCode.REQUEST_PARAMS_IS_NULL);
            result.setMessage("请求参数不合法，请检验。");
            logger.info(JSON.toJSONString(result));
            return result;
        }

        OrderHead orderHeadDb = orderQueryService.findByCode(orderHeadUpdateDTO.getOrderCode(), false, false);
        if (orderHeadDb == null) {
            result = new CommonResult<>(ReturnCode.FIND_ORDER_IS_NULL, orderHeadUpdateDTO.getOrderCode() + " : 用户订单号未查询到订单");
            logger.info(JSON.toJSONString(result));
            return result;
        }

        if (orderHeadDb.getOrderStatus() >= OrderStatus.ORDER_COMMITED_OFC.getIndex()) {
            result = new CommonResult<>(ReturnCode.ORDER_STATUS_ERROR, orderHeadUpdateDTO.getOrderCode() + " : 用户订单已提交DC 不允许修改订单地址信息");
            logger.info(JSON.toJSONString(result));
            return result;
        }

        JSONObject updateAddress = JSON.parseObject(orderHeadUpdateDTO.getAddressInfo());
        // TODO oms特殊处理 2019-01-03 添加，若出现问题，需要更改或删除
        JSONObject orderAddress = JSON.parseObject(orderHeadDb.getAddressInfo());
        Set<Map.Entry<String, Object>> addressEntrySet = orderAddress.entrySet();
        Iterator<Map.Entry<String, Object>> addressEntrys = addressEntrySet.iterator();
        while (addressEntrys.hasNext()) {
            Map.Entry<String, Object> entry = addressEntrys.next();

            String key = entry.getKey();
            if (!updateAddress.containsKey(key)) {
                updateAddress.put(entry.getKey(), entry.getValue());
            }
        }

        orderHeadUpdateDTO.setAddressInfo(updateAddress.toJSONString());

        logger.info(logSign + " --: 更新订单 MIS modify order ohDto -- " + orderHeadUpdateDTO.getOrderCode() + ", params is " + JsonUtils.obj2Json(orderHeadUpdateDTO), LoggerConstant.LOGGER_INFO);
        OrderHead orderHead = new OrderHead();
        BeanUtils.copyProperties(orderHeadUpdateDTO, orderHead);
        logger.info(logSign + " --MIS modify order orderHead -- " + orderHead.getOrderCode() + ", params is " + orderHead.toString(), LoggerConstant.LOGGER_INFO);
        int num = orderUpdateService.updateOrderHead(orderHead.getOrderCode(), orderHead);
        logger.info("OrderCode -- " + orderHead.getOrderCode() + ", update DB num is -- " + num, LoggerConstant.LOGGER_INFO);
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(num == 1);
        result.setMessage("OrderCode -- " + orderHead.getOrderCode() + " 修改成功");
        logger.info(JSON.toJSONString(result));
        return result;
    }

    /**
     * @param orderHeadUpdateDTO
     * @return
     */
    private boolean checkMisOrder(OrderHeadUpdateDTO orderHeadUpdateDTO) {
        if (orderHeadUpdateDTO == null || StringUtils.isEmpty(orderHeadUpdateDTO.getAddressInfo())) {
            return false;
        }
        if (orderHeadUpdateDTO.getOrderCode() == null || orderHeadUpdateDTO.getArea() == null || orderHeadUpdateDTO.getProvince() == null || orderHeadUpdateDTO.getCity() == null || orderHeadUpdateDTO.getDistrict() == null) {
            return false;
        }
        return true;
    }

    /**
     * 仅测试用
     *
     * @param ohDto
     * @return
     */
    @POST
    @Path("update/mis/shophead/admin")
    @Override
    public CommonResult<Object> updateStatusMisShopHeadAdmin(OrderHeadDTO ohDto) {
        long startTimeMs = System.currentTimeMillis();
        String logSign = "logSign:" + ToolService.getLogSign() + ",";
        CommonResult<Object> result = new CommonResult<>();
        if (isPro.equals("1")) {
            result.setCode(ReturnCode.REQUEST_FAIL);
            result.setData(false);
            result.setMessage("此环境不可操作，请检验。");
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
        OrderHead oh = new OrderHead();
        BeanUtils.copyProperties(ohDto, oh);
        if (oh == null || oh.getOrderCode() == null) {
            return null;
        }
        logger.info(logSign + " --MIS admin modify order -- " + oh.getOrderCode() + ", params is " + oh.toString());
        int num = orderUpdateService.updateOrderHead(oh.getOrderCode(), oh);
        //乱，
        logger.info(logSign + " --OrderCode -- " + oh.getOrderCode() + ", update DB num is -- " + num);
        if (num > 0) {
//            UpdateStatusDto dto = new UpdateStatusDto();
//            dto.setStatus(ohDto.getOrderStatus());
//            dto.setOrderNo(ohDto.getParentOrderCode());
            sendEs4order(ohDto.getParentOrderCode(), ohDto.getOrderStatus(), "");
        }
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(num == 1);
        result.setMessage("");
        logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
        return result;
    }

    /**
     * 仅测试用
     *
     * @param ohDto
     * @return
     */
    @POST
    @Path("update/tms/admin")
    @Override
    public CommonResult<Object> updateStatusTmsAdmin(OrderHeadDTO ohDto) {
        long startTimeMs = System.currentTimeMillis();
        String logSign = "logSign:" + ToolService.getLogSign() + ",";
        CommonResult<Object> result = new CommonResult<>();
        if (isPro.equals("1")) {
            result.setCode(ReturnCode.REQUEST_FAIL);
            result.setData(false);
            result.setMessage("此环境不可操作，请检验。");
            logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
            return result;
        }
        OrderHead oh = new OrderHead();
        BeanUtils.copyProperties(ohDto, oh);
        logger.info(logSign + " --TMS admin modify order -- " + oh.getOrderCode() + ", params is " + oh.toString());
        if (oh == null || oh.getOrderCode() == null) {
            return null;
        }
        int num = orderUpdateService.updateOrderHead(oh.getOrderCode(), oh);
        logger.info(logSign + " --OrderCode -- " + oh.getOrderCode() + ", update DB num is -- " + num);
        if (num > 0) {

//            UpdateStatusDto dto = new UpdateStatusDto();
//            dto.setStatus(ohDto.getOrderStatus());
//            dto.setOrderNo(ohDto.getOrderCode());
            sendEs4order(ohDto.getOrderCode(), ohDto.getOrderStatus(), "login");
        }
        result.setCode(ReturnCode.REQUEST_SUCCESS);
        result.setData(num == 1);
        result.setMessage("");
        logger.info(logSign + "请求耗时:" + (startTimeMs - System.currentTimeMillis()) + "ms");
        return result;
    }

    /**
     * 仅测试用
     *
     * @param params
     * @return
     */
    @POST
    @Path("update/dofullreceipt")
    @Override
    public String createSingBill(String params) {
        String url = tmsHost + "/bill/shipping/dofullreceipt";
        ResultVo resultVo = new ResultVo();
        resultVo.set_csrf("");
        resultVo.setRet(1);
        resultVo.setContent("");
        HashMap param = JSON.parseObject(params, HashMap.class);
//        OrderHead orderHead = new OrderHead();
        if (param.get("order_id") == null) {
            resultVo.setMsg("参数有误!");
//            JSONObject jsonResult = JSONObject.fromObject(resultVo);
            return JSON.toJSONString(resultVo);
        }
        Long orderCode = Long.valueOf(param.get("order_id").toString());
        OrderHead reslut = orderQueryService.findByCode(orderCode, false, false);

        if (reslut == null) {
            resultVo.setMsg("订单不存在!");
//            JSONObject jsonResult = JSONObject.fromObject(resultVo);
            return JSON.toJSONString(resultVo);
        } else {
            String requestBody = JsonUtils.obj2Json(param);
            Map<String, String> headMap = new HashMap<>();
            headMap.put("Content-type", "application/json; charset=utf-8");
            headMap.put("Accept", "application/json");
            switch (reslut.getOrderType()) {
                case 1:
                    String res = com.lsh.base.common.net.HttpClientUtils.postBody(url, requestBody, HttpConstant.timeout, HttpConstant.charset, headMap);
                    logger.info("tms返回是: " + res);
                    return res;
                case 2:
                    resultVo.setMsg("HG订单!");
//                    JSONObject jsonResult = JSONObject.fromObject(resultVo);
                    return JSON.toJSONString(resultVo);

                default:
                    resultVo.setMsg("订单类型有误!");
//                    JSONObject jsonRe = JSONObject.fromObject(resultVo);
                    return JSON.toJSONString(resultVo);
            }

        }
    }
}
